// pages/publish/publishTaskEdit.js
const httpUtils = require('../../utils/httpUtils')
const ui = require('../../utils/ui')
const systemInfo = wx.getWindowInfo();
const bottomInset = Math.abs(systemInfo.safeArea.bottom - systemInfo.windowHeight);
var pickerType = 0; //1每人可完成次数 2支持设备 3雇主审核时间 4任务提交时间 5任务持续时间
var againCreate = 0; //是否要重新发布
Page({
  data: {
    categoryName: '',
    serviceFeePercent: '',
    approveDurationOptions: [],
    bidTimesPerUserOptions: [],
    deviceTypes: [],
    submitDurationOptions: [],
    taskDurationOptions: [],
    steps: [],
    agreement: false,
    requirement: '',
    title: '',
    shuoming: '',
    requirement_upload_files: [],
    price: '',
    zongcishu: '',
    dancishu: {},
    deviceType: {},
    guzhushenheshijian: {},
    renwutijiaoshijian: {},
    zongtianshu: {},
    showPicker: false,
    columns: [],
    taskNo: ''
  },
  onLoad(options) {
    this.setData({
      scrollViewBottomInset: bottomInset + 88,
      bottomInset: bottomInset,
      categoryName: options.categoryName,
      serviceFeePercent: options.serviceFeePercent,
      taskNo: options.taskNo,
    })
    againCreate = options.againCreate;
    this.requestConfig();
  },
  onShow() {

  },
  //选择类型
  actionPublishCategory() {
    var that = this;
    wx.navigateTo({
      url: '/pages/publish/publishCategory?edit=1',
      events: {
        acceptDataFromOpenedPage: function (data) { //参数名字随便起，前后页面对应上即可
          //对发送回来的数据进行处理
          console.log(data)
          that.setData({
            categoryName: data.categoryName,
            serviceFeePercent: data.serviceFeePercent,
          })
        }
      }
    })
  },
  //添加步骤
  actionAddStep() {
    var that = this;
    wx.showActionSheet({
      itemList: ['图文说明', '网址链接', '复制信息'],
      success(res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            wx.navigateTo({
              url: '/pages/publish/addSteps/addStepNormal',
              events: {
                acceptDataFromStepNormal: function (data) {
                  console.log(data)
                  const {
                    steps = []
                  } = that.data;
                  steps.push(data);
                  that.setData({
                    steps
                  });
                }
              }
            })
          } else if (res.tapIndex == 1) {
            wx.navigateTo({
              url: '/pages/publish/addSteps/addStepLink',
              events: {
                acceptDataFromStepLink: function (data) {
                  console.log(data)
                  const {
                    steps = []
                  } = that.data;
                  steps.push(data);
                  that.setData({
                    steps
                  });
                }
              }
            })
          } else if (res.tapIndex == 2) {
            wx.navigateTo({
              url: '/pages/publish/addSteps/addStepCopy',
              events: {
                acceptDataFromStepCopy: function (data) {
                  const {
                    steps = []
                  } = that.data;
                  steps.push(data);
                  that.setData({
                    steps
                  });
                }
              }
            })
          }
        }
      }
    })
  },
  //获取配置选项信息
  requestConfig() {
    let obj = {
      method: 'GET',
      url: '/task/select-options',
      data: {
        categoryName: this.data.categoryName
      }
    }
    httpUtils.request(obj).then(res => {
      this.setData({
        approveDurationOptions: res.data.approveDurationOptions,
        bidTimesPerUserOptions: res.data.bidTimesPerUserOptions,
        deviceTypes: res.data.deviceTypes,
        submitDurationOptions: res.data.submitDurationOptions,
        taskDurationOptions: res.data.taskDurationOptions,
        dancishu: res.data.bidTimesPerUserOptions[0],
        deviceType: res.data.deviceTypes[0],
        guzhushenheshijian: res.data.approveDurationOptions[0],
        renwutijiaoshijian: res.data.submitDurationOptions[0],
        zongtianshu: res.data.taskDurationOptions[0],
      })
      //如果taskno有值，说明是重新编辑任务，需要请求数据
      if (this.data.taskNo.length > 0) {
        this.reqeustPublishTaskInfo();
      }
    }).catch(err => {
      console.log(err)
    });
  },
  //请求编辑任务数据
  reqeustPublishTaskInfo() {
    let obj = {
      method: 'GET',
      url: '/task/published/' + this.data.taskNo,
      data: {}
    }
    httpUtils.request(obj).then(res => {
      var stepArr = [];
      res.data.taskStepList.forEach(element => {
        if (element.taskStepType == 'CONTENT') {
          var imageArr = [];
          element.taskStepImages.forEach(element => {
            imageArr.push({
              upload_url: element,
              url: element
            })
          });
          stepArr.push({
            type: 'normal',
            content: element.taskDescription,
            images: imageArr
          })
        } else if (element.taskStepType == 'LINK') {
          stepArr.push({
            type: 'link',
            content: element.taskDescription,
            link: element.taskLinks[0]
          })
        } else if (element.taskStepType == 'INFO') {
          stepArr.push({
            type: 'copy',
            content: element.taskDescription,
            copy: element.taskCopyInfo
          })
        }
      });
      var requirementImageArr = [];
      res.data.taskRequirementImages.forEach(element => {
        requirementImageArr.push({
          upload_url: element,
          url: element
        })
      });
      this.setData({
        categoryName: res.data.taskCategory,
        steps: stepArr,
        requirement: res.data.taskRequirement,
        title: res.data.taskTitle,
        shuoming: res.data.taskDescription,
        requirement_upload_files: requirementImageArr,
        price: res.data.sourceAmount,
        zongcishu: res.data.originalBidTime,
        dancishu: this.getBidTimesPerUserOptions(res.data.bidTimesByUser),
        deviceType: this.getDeviceTypesOptions(res.data.deviceType),
        guzhushenheshijian: this.getApproveDurationOptions(res.data.ownerApproveDurationHours),
        renwutijiaoshijian: this.getSubmitDurationOptions(res.data.bidSubmitDurationHours),
        zongtianshu: this.getTaskDurationOptions(res.data.taskDurationHours),
      })

    }).catch(err => {
      console.log(err)
    });
  },
  //获取每个人完成次数结构
  getBidTimesPerUserOptions(value) {
    var option = {};
    this.data.bidTimesPerUserOptions.forEach(element => {
      if (element.optionValue === value) {
        option = element;
      }
    });
    return option;
  },
  //获取设备结构
  getDeviceTypesOptions(value) {
    var option = {};
    this.data.deviceTypes.forEach(element => {
      if (element.optionValue === value) {
        option = element;
      }
    });
    return option;
  },
  //获取雇主审核时间结构
  getApproveDurationOptions(value) {
    var option = {};
    this.data.approveDurationOptions.forEach(element => {
      if (element.optionValue === value) {
        option = element;
      }
    });
    return option;
  },
  //获取任务审核时间结构
  getSubmitDurationOptions(value) {
    var option = {};
    this.data.submitDurationOptions.forEach(element => {
      if (element.optionValue === value) {
        option = element;
      }
    });
    return option;
  },
  //获取任务天数结构
  getTaskDurationOptions(value) {
    var option = {};
    this.data.taskDurationOptions.forEach(element => {
      if (element.optionValue === value) {
        option = element;
      }
    });
    return option;
  },
  //点击图片预览
  previewImage(event) {
    var currentUrl = event.currentTarget.dataset.src //获取当前点击图片链接
    var urls = event.currentTarget.dataset.urls //获取当前图片列表
    wx.previewImage({
      current: currentUrl, //当前点击的预览图片地址
      urls: urls, //需要预览的图片列表，这是必须设置的属性
    })
  },
  //步骤图文编辑
  add_edit(event) {
    var that = this;
    if (that.data.steps[event.currentTarget.dataset.index].type == 'normal') {
      wx.navigateTo({
        url: '/pages/publish/addSteps/addStepNormal',
        events: {
          acceptDataFromStepNormal: function (data) {
            console.log(data)
            const {
              steps = []
            } = that.data;
            steps[event.currentTarget.dataset.index] = data;
            that.setData({
              steps
            });
          }
        },
        success: function (res) {
          res.eventChannel.emit('stepEditInfo', that.data.steps[event.currentTarget.dataset.index]);
        }
      })
    } else if (that.data.steps[event.currentTarget.dataset.index].type == 'link') {
      wx.navigateTo({
        url: '/pages/publish/addSteps/addStepLink',
        events: {
          acceptDataFromStepLink: function (data) {
            console.log(data)
            const {
              steps = []
            } = that.data;
            steps[event.currentTarget.dataset.index] = data;
            that.setData({
              steps
            });
          }
        },
        success: function (res) {
          res.eventChannel.emit('stepEditInfo', that.data.steps[event.currentTarget.dataset.index]);
        }
      })
    } else if (that.data.steps[event.currentTarget.dataset.index].type == 'copy') {
      wx.navigateTo({
        url: '/pages/publish/addSteps/addStepCopy',
        events: {
          acceptDataFromStepCopy: function (data) {
            console.log(data)
            const {
              steps = []
            } = that.data;
            steps[event.currentTarget.dataset.index] = data;
            that.setData({
              steps
            });
          }
        },
        success: function (res) {
          res.eventChannel.emit('stepEditInfo', that.data.steps[event.currentTarget.dataset.index]);
        }
      })
    }

  },
  //步骤删除
  add_delete(event) {
    wx.showModal({
      title: '提示',
      content: '确定要删除该步骤？',
      complete: (res) => {
        if (res.confirm) {
          const {
            steps = []
          } = this.data;
          steps.splice(event.currentTarget.dataset.index, 1);
          this.setData({
            steps
          });
        }
      }
    })
  },
  //线上发布协议
  agreementPress() {
    wx.navigateTo({
      url: '/pages/login/showWeb?url=https://www.shangjinxia.ltd/app_task/fabuProtocol/index.html',
    })
  },
  //点击是否同意协议
  agreePress() {
    this.setData({
      agreement: true,
    });
  },
  disagreePress() {
    this.setData({
      agreement: false,
    });
  },
  //发布任务
  actionPublishTask() {
    if (!this.checkInput()) {
      return;
    }
    if (!this.data.agreement) {
      wx.showModal({
        title: '提示',
        content: '需要勾选同意《线上发布协议》才可以进行发布操作',
        confirmText: '同意',
        complete: (res) => {
          if (res.confirm) {
            this.setData({
              agreement: true,
            });
          }
        }
      });
      return;
    }
    var stepArr = [];
    this.data.steps.forEach(element => {
      if (element.type == 'normal') {
        var images = [];
        element.images.forEach(element => {
          images.push(element.upload_url);
        });
        stepArr.push({
          taskStepType: 'CONTENT',
          taskStepImages: images,
          taskDescription: element.content
        });
      } else if (element.type == 'copy') {
        stepArr.push({
          taskStepType: 'INFO',
          taskCopyInfo: element.copy,
          taskDescription: element.content
        });
      } else if (element.type == 'link') {
        stepArr.push({
          taskStepType: 'LINK',
          taskLinks: [element.link],
          taskDescription: element.content
        });
      }
    });
    var requirementImageArr = [];
    this.data.requirement_upload_files.forEach(element => {
      requirementImageArr.push(element.upload_url);
    });
    var data = {
      taskCategory: this.data.categoryName,
      taskDescription: this.data.shuoming,
      taskTitle: this.data.title,
      taskStepCreateDtos: stepArr,
      taskRequirement: this.data.requirement,
      taskRequirementImages: requirementImageArr,
      deviceType: this.data.deviceType.optionValue,
      sourceAmount: this.data.price,
      originalBidTime: this.data.zongcishu,
      bidTimesByUser: this.data.dancishu.optionValue,
      approveByOwner: true,
      ownerApproveDurationHours: this.data.guzhushenheshijian.optionValue,
      bidSubmitDurationHours: this.data.renwutijiaoshijian.optionValue,
      taskDurationHours: this.data.zongtianshu.optionValue
    };
    //如果任务编号存在，就是编辑更新任务
    if (this.data.taskNo == null || parseInt(againCreate) == 1) {
      let obj = {
        method: 'POST',
        url: '/task',
        showLoading: true,
        data: data
      }
      httpUtils.request(obj).then(res => {
        wx.navigateTo({
          url: '/pages/publish/publishSuccess',
        })
      }).catch(err => {
        console.log(err)
      });
    } else {
      let obj = {
        method: 'PUT',
        url: '/task/published/'+this.data.taskNo,
        showLoading: true,
        data: data
      }
      httpUtils.request(obj).then(res => {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000,
          mask: true,
          success: function() {
            setTimeout(function() {
              wx.navigateBack({
                delta: 0,
              });
            }, 1500)
          }
        });
      }).catch(err => {
        console.log(err)
      });
    }
    
  },
  actionPreview() {
    if (!this.checkInput()) {
      return;
    }
    var that = this;
    wx.navigateTo({
      url: '/pages/publish/preview/publishPreview',
      success: function (res) {
        res.eventChannel.emit('taskInfo', {
          task_title: that.data.title,
          task_time: that.data.renwutijiaoshijian.optionDisplay,
          task_surplus: that.data.zongcishu,
          task_price: that.data.price,
          icon_view_bid: that.data.dancishu.optionDisplay,
          task_description: that.data.shuoming,
          steps: that.data.steps,
          task_requirement: that.data.requirement,
          requirement_images: that.data.requirement_upload_files
        });
      }
    })
  },
  //检查输入内容
  checkInput() {
    if (this.data.title.length == 0) {
      ui.showToast("请输入标题");
      return false;
    }
    if (this.data.shuoming.length == 0) {
      ui.showToast("请输入任务说明");
      return false;
    }
    if (this.data.steps.length == 0) {
      ui.showToast("任务步骤不能为空");
      return false;
    }
    if (this.data.requirement.length == 0) {
      ui.showToast("请输入任务要求");
      return;
    }
    if (this.data.price.length == 0) {
      ui.showToast("请输入任务单价");
      return false;
    }
    if (this.data.zongcishu.length == 0) {
      ui.showToast("请输入任务总次数");
      return false;
    } else if (this.data.zongcishu < 10) {
      ui.showToast("任务次数不能低于10");
      return false;
    }
    return true;
  },
  //图片选择后
  afterRead(event) {
    var that = this;
    const {
      file
    } = event.detail;
    wx.uploadFile({
      url: 'https://shangjinxia.ltd/api/image/file',
      filePath: file.url,
      name: 'file',
      formData: {},
      success(res) {
        // 上传完成需要更新 upload_files
        var result = JSON.parse(res.data);
        const {
          requirement_upload_files = []
        } = that.data;
        requirement_upload_files.push({
          ...file,
          url: file.thumb,
          upload_url: result.uploadFileUrl
        });
        that.setData({
          requirement_upload_files
        });
      },
      fail() {
        ui.showToast('上传失败');
      }
    });
  },
  deleteImage(event) {
    const {
      requirement_upload_files = []
    } = this.data;
    requirement_upload_files.splice(event.detail.index);
    this.setData({
      requirement_upload_files
    });
  },
  //查看服务费规则
  actionShowPriceFee() {
    wx.navigateTo({
      url: '/pages/login/showWeb?url=https://www.shangjinxia.ltd/app_task/serviceFeeDescription.html',
    })
  },
  //选择任务次数
  actionChooseCishu() {
    pickerType = 1;
    var options = [];
    this.data.bidTimesPerUserOptions.forEach(element => {
      options.push(element.optionDisplay);
    });
    this.setData({
      showPicker: true,
      columns: options
    })
  },
  //选择设备
  actionChooseDevice() {
    pickerType = 2;
    var options = [];
    this.data.deviceTypes.forEach(element => {
      options.push(element.optionDisplay);
    });
    this.setData({
      showPicker: true,
      columns: options
    })
  },
  //雇主审核时间
  actionChooseGuzhushenheshijian() {
    pickerType = 3;
    var options = [];
    this.data.approveDurationOptions.forEach(element => {
      options.push(element.optionDisplay);
    });
    this.setData({
      showPicker: true,
      columns: options
    })
  },
  //任务提交时间
  actionChooseRenwutijiaoshijian() {
    pickerType = 4;
    var options = [];
    this.data.submitDurationOptions.forEach(element => {
      options.push(element.optionDisplay);
    });
    this.setData({
      showPicker: true,
      columns: options
    })
  },
  //任务持续天数
  actionChooseZongtianshu() {
    pickerType = 5;
    var options = [];
    this.data.taskDurationOptions.forEach(element => {
      options.push(element.optionDisplay);
    });
    this.setData({
      showPicker: true,
      columns: options
    })
  },
  onClose() {
    this.setData({
      showPicker: false
    });
  },
  onConfirm(event) {
    if (pickerType == 1) {
      this.setData({
        dancishu: this.data.bidTimesPerUserOptions[event.detail.index],
        showPicker: false
      })
    } else if (pickerType == 2) {
      this.setData({
        deviceType: this.data.deviceTypes[event.detail.index],
        showPicker: false
      })
    } else if (pickerType == 3) {
      this.setData({
        guzhushenheshijian: this.data.approveDurationOptions[event.detail.index],
        showPicker: false
      })
    } else if (pickerType == 4) {
      this.setData({
        renwutijiaoshijian: this.data.submitDurationOptions[event.detail.index],
        showPicker: false
      })
    } else if (pickerType == 5) {
      this.setData({
        zongtianshu: this.data.taskDurationOptions[event.detail.index],
        showPicker: false
      })
    }
  },
})